package observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 环境传感器基类
 * 实现观察者模式的被观察者角色
 */
public class EnvironmentSensor {
    private final String sensorType;
    private final List<EnvironmentObserver> observers = new ArrayList<>();
    private double currentValue;

    public EnvironmentSensor(String sensorType) {
        this.sensorType = sensorType;
    }

    public void addObserver(EnvironmentObserver observer) {
        observers.add(observer);
    }

    public void removeObserver(EnvironmentObserver observer) {
        observers.remove(observer);
    }

    public void setValue(double newValue) {
        if (currentValue != newValue) {
            currentValue = newValue;
            notifyObservers();
        }
    }

    private void notifyObservers() {
        for (EnvironmentObserver observer : observers) {
            observer.update(sensorType, currentValue);
        }
    }

    public double getCurrentValue() {
        return currentValue;
    }


}
